<?php

namespace addons\booking\controller;

use addons\booking\model\House as HouseModel;
use addons\booking\model\OrderCalendar;
use addons\booking\model\Lodgers;
use addons\booking\model\Collect;
use addons\booking\model\Config;
use addons\booking\model\Fields;
use addons\booking\model\Calendar;
use addons\booking\model\Coupon;
use addons\booking\model\UserCoupon;
use addons\booking\model\CouponCondition;
use addons\booking\library\IntCode;
use addons\booking\model\Store;

class House extends Base
{
    protected $noNeedLogin = ['condition', 'houseList', 'houseSelect', 'detail', 'booking', 'monthHouse'];

    /**
     * 排序，筛选条件
     */
    public function condition()
    {
        $filterList = Config::with([
            'sons' => function ($query) {
                $query->field('id,type,name');
            }
        ])->field('id,type')->where('type', 'in', ['house', 'tag', 'floor', 'facility'])->group('type')->select();

        foreach ($filterList as &$item) {
            switch ($item['type']) {
                case 'house':
                    $item['label'] = '房型';
                    break;
                case 'tag':
                    $item['label'] = '特色标签';
                    break;
                case 'floor':
                    $item['label'] = '楼层';
                    break;
                case 'facility':
                    $item['label'] = '配套设施';
                    break;
            }
            $sons = collection($item['sons'])->toArray();
            $sons = array_merge([['id' => 0, 'name' => '全部', 'type' => '', 'type_text' => '']], $item['sons']);
            $item['value'] = $sons;
            unset($item['sons']);
        }

        $orderList = [
            'weigh'      => '推荐排序',
            'comment'    => '好评优先',
            'low_price'  => '低价优先',
            'high_price' => '高价优先',
            'views'      => '人气优先',
            'distance'   => '距离优先'
        ];
        
        $meter = [1,5,10,30,50,80,100,200];
        
        $money = ["0-100","100-500","500-1000","1000-1500","1500-2000","2000-10000000"];

        $this->success('获取成功', [
            'orderList'  => $orderList,
            'filterList' => $filterList,
            'money'=>$money,
            'meter'=>$meter,
        ]);
    }

    /**
     * 房间列表
     */
    public function houseList()
    {
        $calendar = $this->request->param('calendar');
        if (!empty($calendar)) {
            $calendar = explode('/', $calendar);
            if (count($calendar) == 2) { //时间范围
                $time = strtotime($calendar[1]);
                if ($time < time()) {
                    $this->error('不能查询过去的房间状态');
                }
            }
        }
        $list = HouseModel::tableList($this->request->param());
        if ($this->auth->isLogin()) {
            Collect::render($list, $this->auth->id, 0);
        }
        $this->success('', $list);
    }

    public function houseSelect()
    {
        $this->success('', HouseModel::field('id,name,room')->where('status', 'up')->select());
    }

    /**
     * 房间详情
     */
    public function detail()
    {
        $id = $this->request->param('id/d');
        if (empty($id)) {
            $this->error('参数缺失');
        }
        $data = HouseModel::getDetail($id);
        if (!$data) {
            $this->error('记录未找到');
        }
        $data->setInc('views');
        //设施
        $data->facility = Config::where('type', 'facility')->field('id,name,image')->select();
        //自定义字段
        $data->fields = Fields::getSourceField($id);
        //是否收藏
        $data->isCollect = Collect::isCollect(0, $id);
        //优惠券
        $conditions = CouponCondition::getHouseCondition($id, $data['store_id']);
        $sql = "condition_ids IS NULL OR condition_ids=''";
        foreach ($conditions as $key => $item) {
            $item['id'] = (int)$item['id'];
            $sql .= " OR FIND_IN_SET('{$item['id']}',condition_ids)";
        }
        $list = Coupon::field('id,name,result,result_data,alone_num,receive_times,mode,createtime,received_num,give_num')->where($sql)->select();
        //已经登录，渲染已领的优惠券
        $coupon_ids = [];
        if ($this->auth->isLogin()) {
            $coupon_ids = UserCoupon::where('user_id', $this->auth->id)->column('coupon_id');
        }
        $newList = [];
        foreach ($list as $item) {
            Coupon::render($item, $coupon_ids);
            $item->id = IntCode::encode($item->id);
            $newList[] = $item;
        }
        unset($list);

        $data->coupon = $newList;
        $this->success('', $data);
    }

    /**
     * 一个月的房间信息
     */
    public function monthHouse()
    {
        $year = $this->request->param('year');
        $month = $this->request->param('month');
        $store_id = $this->request->param('store_id');
        // $city = $this->request->param('city');
        // $store_ids = [];
        // if(!isset($store_id)&&isset($city)){
        //     $store_ids = Store::where("address like '%".$city."%'")->column("id");
        //     // var_dump($store_ids);die;
        // }
        $y = $year;
        $m = $month;

        $toDay = date('d');
        $nowYear = date('Y');
        $nowMonth = date('m');

        if ($year < $nowYear || ($year == $nowYear && $m < $nowMonth)) {
            $this->error('无法查找过去的房间状态');
        }
        if (!$year) {
            $year = $nowYear;
        }
        if (!$month) {
            $month = $nowMonth;
        }
        $firstDay = strtotime("{$year}-{$month}-01");
        if ($month == 12) {
            $month = 1;
            $year += 1;
        } else {
            $month += 1;
        }

        $lastDay = strtotime("{$year}-{$month}-01");

        $calendar = OrderCalendar::field("id,from_unixtime(reserve_time,'%d') day,GROUP_CONCAT(house_id) house_ids")
            ->where('reserve_time', '>=', $firstDay)
            ->where('reserve_time', '<', $lastDay)
            ->where('status', 'normal')
            ->group('day')
            ->select();

        $newCalendar = [];
        //以天为键重新组合
        foreach ($calendar as $item) {
            $newCalendar[$item['day']] = explode(',', $item['house_ids']);
        }
        unset($calendar);
        $time = 24 * 60 * 60;

        //找日历价格的最低价
        $minPrices = Calendar::field("min(price) min_price,FROM_UNIXTIME(day_time,'%d') day")->where('day_time', '>=', $firstDay)->where('day_time', '<', $lastDay)->group('day')->select();
        $newMinPrices = [];
        foreach ($minPrices as $item) {
            $newMinPrices[$item['day']] = $item['min_price'];
        }

        $house = HouseModel::field('id,price')->where(function ($query) use ($store_id) {
            if ($store_id) {
                $query->where('store_id', $store_id);
            }
            // if($store_ids){
            //      $query->where('store_id in ('.implode(',',$store_ids).')');
            // }
        })->select();

        //一个月的日历
        $days = [];
        for ($i = $firstDay; $i < $lastDay; $i += $time) {
            $t = date('d', $i);
            $min_price1 = isset($newMinPrices[$t]) ? $newMinPrices[$t] : 0;
            $dayData = [];
            //有被预订，排除
            if (isset($newCalendar[$t])) {
                foreach ($house as $res) {
                    if (!in_array($res['id'], $newCalendar[$t])) {
                        $dayData[] = $res; //最后的房间
                    }
                }
            } else {
                $dayData = $house;
            }
            $row = array_column($dayData, 'price');
           
            if (!empty($row)) {
                $min_price2 = min($row);
            } else {
                $min_price2 = 0;
            }
            $days[$t] = [
                'price' => (int)(($nowYear == $y && $nowMonth == $m && $toDay > $t) ? 0 : ($min_price1 == 0 ? $min_price2 : ($min_price1 < $min_price2 ? $min_price1 : $min_price2)))
            ];
        }

        $this->success('', $days);
    }

    /**
     * 预定前判断
     */
    public function booking()
    {
        $id = $this->request->post('id/d');
        if (empty($id)) {
            $this->error('参数缺失');
        }
        $start_time = $this->request->post('start_time');
        $end_time = $this->request->post('end_time');
        if (empty($start_time) || empty($end_time)) {
            $this->error('请选择入住和离店日期');
        }
        //判断数据格式是否正确
        if (!checkDateFormat($start_time) || !checkDateFormat($end_time)) {
            $this->error('日期格式不正确');
        }
        $detail = HouseModel::getDetail($id);
        if (!$detail) {
            $this->error('房间不存在或未上架');
        }
        //寻找日期范围是否有被预定
        if (OrderCalendar::isHasBooked($id, $start_time, $end_time)) {
            $this->error('此时间区域未有房间可预定');
        }
        //如果登录的话，取优惠券
        if ($this->auth->isLogin()) {
            $detail->coupon = UserCoupon::myHouseCoupon($this->auth->id, $id, $detail['store_id']);
        } else {
            $detail->coupon = [];
        }
        $this->success('获取成功！', [
            'detail' => $detail,
            'lodger' => Lodgers::field('id,name')->where('user_id', $this->auth->id)->select()
        ]);
    }

    /**
     * 获取用户的住客信息
     */
    public function lodgerList()
    {
        $param = $this->request->param();
        $param['user_id'] = $this->auth->id;
        $this->success('', Lodgers::tableList($param));
    }

    /**
     * 添加或编辑住客信息
     */
    public function addOrEditLodger()
    {
        $name = $this->request->post('name');
        $type = $this->request->post('type/d');
        $idnumber = $this->request->post('idnumber');
        $mobile = $this->request->post('mobile/d');
        $id = $this->request->post('id/d');
        if (!$name) {
            $this->error('姓名不能为空！');
        }
        if (!$idnumber) {
            $this->error('证件号码不能为空！');
        }
        if ($id) {
            $data = Lodgers::where('id', $id)->where('user_id', $this->auth->id)->find();
            if (!$data) {
                $this->error('未找到记录');
            }
            $status = (new Lodgers)->save([
                'name'     => $name,
                'type'     => $type,
                'mobile'   => $mobile,
                'idnumber' => $idnumber,
                'user_id'  => $this->auth->id,
            ], ['id' => $id]);
        } else {
            $status = (new Lodgers)->save([
                'name'     => $name,
                'type'     => $type,
                'idnumber' => $idnumber,
                'mobile'   => $mobile,
                'user_id'  => $this->auth->id,
            ]);
        }
        if ($status) {
            $this->success('提交成功');
        }
        $this->error('提交失败');
    }

    /**
     * 住客信息
     */
    public function delLodger()
    {
        $id = $this->request->post('id/d');
        if (!$id) {
            $this->error('参数错误');
        }
        $data = Lodgers::where('id', $id)->where('user_id', $this->auth->id)->find();
        if ($data) {
            $data->delete();
            $this->success('删除成功!');
        }
        $this->error('未找到记录');
    }

    /**
     * 住客信息
     */
    public function getLodger()
    {
        $id = $this->request->get('id/d');
        $data = Lodgers::where('id', $id)->where('user_id', $this->auth->id)->find();
        if ($data) {
            $this->success('获取成功', $data);
        }
        $this->error('未找到记录');
    }

}
